package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.dto.UserWareHouseDTO;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.entity.UserWarehouse;
import com.scs.application.modules.base.entity.Warehouse;
import com.scs.application.modules.base.mapper.UserWarehouseMapper;
import com.scs.application.modules.base.mapper.WarehouseMapper;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.base.service.UserWarehouseService;
import com.scs.application.modules.base.vo.UserWarehouseVO;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class UserWarehouseServiceImpl extends BaseServiceImpl<UserWarehouseMapper, UserWarehouse> implements UserWarehouseService {

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private DeptService deptService;

    @Override
    public List<UserWarehouseVO> getUserWarehouse() {

        if(UserUtils.isAdmin()) {
            List<Warehouse> warehouses = warehouseMapper.selectList(new QueryWrapper<>());
            List<Dept> deptList = deptService.list(new QueryWrapper<Dept>().isNotNull("warehouse_id"));
            List<UserWarehouseVO> result = Lists.newArrayListWithExpectedSize(warehouses.size());
            for (Warehouse warehouse : warehouses) {
                UserWarehouseVO vo = new UserWarehouseVO();
                vo.setId(warehouse.getId());
                vo.setWarehouseId(warehouse.getId());
                vo.setWarehouseName(warehouse.getName());
                vo.setWarehouseCode(warehouse.getCode());
                vo.setApplyWarehouseId(warehouse.getApplyWarehouseId());
                vo.setApplyWarehouseName(warehouse.getApplyWarehouseName());
                vo.setFlagCenter(warehouse.getFlagCenter());
                vo.setFlagDisinfection(warehouse.getFlagDisinfection());

                Dept dept = deptList.stream().filter(dept1 -> warehouse.getId().equals(dept1.getWarehouseId())).findAny().orElse(null);
                if (dept != null) {
                    vo.setDeptId(dept.getId());
                    vo.setDeptName(dept.getName());
                }
                result.add(vo);
            }
            return result;
        }

        return baseMapper.getUserWarehouse(UserUtils.currentUser().getId(),UserUtils.currentUser().getOfficeId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setUserWareHouse(UserWareHouseDTO userWareHouseDTO) {
        //删除已选则的

        if(userWareHouseDTO.getWarehouseIdList()==null || userWareHouseDTO.getWarehouseIdList().size() <1){
            super.remove(new QueryWrapper<UserWarehouse>()
                    .eq(userWareHouseDTO.getSetTypeField(),userWareHouseDTO.getId())
                    );
            return;
        }else{
            super.remove(new QueryWrapper<UserWarehouse>()
                    .eq(userWareHouseDTO.getSetTypeField(),userWareHouseDTO.getId())
                    .notIn("warehouse_id",userWareHouseDTO.getWarehouseIdList()));
        }


        //科室设置仓库时，校验是否被占用
        if(userWareHouseDTO.getSetTypeField().equalsIgnoreCase("dept_id") ){
            int count=this.count(Wrappers.<UserWarehouse>query().ne("dept_id",userWareHouseDTO.getId()). in("warehouse_id",userWareHouseDTO.getWarehouseIdList()) );
            if(count>0) throw new BusinessException("您所选择的仓库列表有"+count+"个已被其他科室选择，请刷新数据后重新选择");
        }

        //新增
        userWareHouseDTO.getWarehouseIdList().stream().filter(item->
            baseMapper.selectCount(new QueryWrapper<UserWarehouse>()
                    .eq(userWareHouseDTO.getSetTypeField(),userWareHouseDTO.getId())
                    .eq("warehouse_id", item)) == 0
        ).forEach(item -> {
            UserWarehouse userWarehouse = new UserWarehouse();
            userWarehouse.setWarehouseId(item);
            if(userWareHouseDTO.getSetTypeField().equalsIgnoreCase("dept_id")){
                userWarehouse.setType("dept");
                userWarehouse.setDeptId(userWareHouseDTO.getId());
            }else{
                userWarehouse.setType("user");
                userWarehouse.setUserId(userWareHouseDTO.getId());
            }
            super.save(userWarehouse);
        });

    }

    @Override
    public List<UserWarehouseVO> getUserWarehouseBySettype(String sql) {
        return baseMapper.getUserWarehouseBySettype(sql);
    }
}
